/**
 * Created by lll on 2017/4/20.
 */
var board = new Array();
var score = 0;
var hasConflicted = new Array();
$(document).ready(function(){
    $("body").on("touchmove",function(event){
        event.preventDefault();
    });
    prepareForMobile() ;
    newgame();
});

function prepareForMobile(){
    if( documentWidth >= 500 ){
        gridContainerWidth = 500 ;
        cellSideLength = 100 ;
        cellSpace = 20 ;
    }
    else{
        $(" #grid-container ").css({
            'width' : gridContainerWidth -2 * cellSpace ,
            'height' : gridContainerWidth - 2 * cellSpace ,
            'padding' : cellSpace ,
            'border-radius' : 0.02 * gridContainerWidth
        }) ;
        $(" .grid-cell").css({
            'width' : cellSideLength ,
            'height' : cellSideLength ,
            'border-radius' : 0.02 * cellSideLength

        });
    }
}
 //新游戏开始功能
 function newgame(){
     //初始化棋盘
     $(".mask").hide();
     $(".success").hide();
     $(".fail").hide();
     init();
     //在随机两个点生成数字
     generateOneNumber();
     generateOneNumber();
 }
 //初始化功能
 function init(){
     for(var i = 0;i <4; i++){
         for(var j = 0; j<4; j++){
             var gridCell = $('#grid-cell-'+i+'-'+j);
             gridCell.css({
                 "top": getPosTop(i,j),
                 "left": getPosLeft(i,j)
             });
         }
     }
     for(var i = 0; i<4; i++){
         board[i] = new Array();
         hasConflicted[i] = new Array() ;
         for(var j = 0; j<4; j++){
             board[i][j] = 0;
             hasConflicted[i][j] = false;
         }
     }
     updateBoardView();
     score = 0 ;
     $(".fail").css("display","none");
     $(".success").css("display","none");
 }
 //初始化棋盘并添加元素
 function updateBoardView(){
     $(".number-cell").remove();
     for(var i = 0; i<4; i++){
         for(var j = 0; j<4; j++){
             $("#grid-container").append('<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>');
             var theNumberCell = $('#number-cell-'+i+'-'+j);
             if(board[i][j] == 0){
                 theNumberCell.css({
                     "width": '0px',
                     "height": '0px',
                     "top":getPosTop(i,j) + cellSideLength / 2 ,
                     "left":getPosLeft(i,j) + cellSideLength / 2
                 });
             }
             else{
                 theNumberCell.css({
                     "width": cellSideLength ,
                     "height": cellSideLength ,
                     "top":getPosTop(i,j),
                     "left":getPosLeft(i,j),
                     "background-color":getNumberBackgroundColor(board[i][j]),
                     "color":getNumberColor(board[i][j])
                 });
                 theNumberCell.text(board[i][j]);
             }
             hasConflicted[i][j] = false;
         }
     }
     $(" .number-cell ").css({
         'line-height' : cellSideLength + 'px',
         'font-size' : 0.4 * cellSideLength + 'px'
     });
 }
 function generateOneNumber(){
     var tempBoard = new Array();
     if( nospace ( board ) ) {
         return false;
     }
     // 随机一个位置
     for( var i = 0 ; i < 4; i++ ){
         for( var j = 0; j < 4 ; j++){
             if( board[i][j] == 0){
                 tempBoard.push( i * 4 + j );
             }
         }
     }
     var temp = Math.floor( Math.random() * tempBoard.length );
     var randx = Math.floor( tempBoard[temp] / 4 ) ;
     var randy = Math.floor( tempBoard[temp] % 4 ) ;

     //随机一个数字
     var randNumber = Math.random() <= 0.5 ? 2 : 4;

     //在随机位置上随机一个数字
     board[randx][randy] = randNumber;
     showNumberWithAnimation( randx, randy, randNumber );

     return true;
 }
 $(document).keydown(function(event){

     switch(event.keyCode){
         case 37:     //left按键
             event.preventDefault();
             if(moveLeft()){
            setTimeout("generateOneNumber()",210);
            setTimeout("isGameOver", 300);
             }
             break;
         case 38:      //up按键
             event.preventDefault();
             if(moveUp()){
                 setTimeout("generateOneNumber()",210);
                 setTimeout("isGameOver", 300);
             }
             break;
         case 39:     //right按键
             event.preventDefault();
             if(moveRight()){
                 setTimeout("generateOneNumber()",210);
                 setTimeout("isGameOver", 300);
             }
             break;
         case 40:     //down按键
             event.preventDefault();
             if(moveDown()){
                 setTimeout("generateOneNumber()",210);
                 setTimeout("isGameOver", 300);
             }
             break;
         default:
             break;
     }
 });

 document.addEventListener('touchstart' , function(event){
     startx = event.touches[0].pageX;
     starty = event.touches[0].pageY;
 });

/*document.addEventListener( 'touchmove' , function(event){
    event.preventDefault();
});*/
 document.addEventListener('touchend' , function( event ){
     endx = event.changedTouches[0].pageX;
     endy = event.changedTouches[0].pageY;
     var deltax = endx - startx ;
     var deltay = endy - starty ;

     if( Math.abs( deltax ) < 0.2 * documentWidth && Math.abs( deltay ) < 0.2 * documentWidth){
         return;
     }
      else{
     //x
     if( Math.abs( deltax ) >= Math.abs( deltay )){
         if( deltax > 0 ){
             //向右滑动
             if( moveRight() ){
                 setTimeout( 'generateOneNumber()', 210);
                 setTimeout(' isGameOver()' , 300);
             }
         }
         else{
             //向左滑动
             if( moveLeft() ){
                 setTimeout( 'generateOneNumber()', 210);
                 setTimeout(' isGameOver()' , 300);
             }
         }
     }
     else{
         if( deltay > 0 ){
             //向下滑动
             if( moveDown() ){
                 setTimeout( 'generateOneNumber()', 210);
                 setTimeout(' isGameOver()' , 300);
             }
         }
         else{
             //向上滑动
             if( moveUp() ){
                 setTimeout( 'generateOneNumber()', 210);
                 setTimeout(' isGameOver()' , 300);
             }
         }
     }
     }
 });

 function isGameOver(){
     if(nospace( board ) && nomove( board )){
         gameOver();
     }
     for(var i = 0; i < 4; i++){
         for(var j = 0; j < 4; j++){
             if( board[i][j] == 2048 ){
                 winGame();
             }
         }
     }
 }


 function gameOver(){
     $(".mask").show();
     $(".fail").show();
 }
 function winGame(){
     $(".mask").show();
     $(".success").show();
 }

 function moveLeft(){
     if( !canMoveLeft(board)){
         return false;
     }
     //向左移动
     for( var i = 0 ; i < 4 ; i++ ){
         for( var j = 1 ; j < 4 ; j ++ ){
             if( board[i][j] != 0){
                 for( var k = 0 ; k < j ; k++ ){
                     if( board[i][k] == 0 && noBlockHorizontal( i , k , j , board ) ){
                         //可以移动
                         showMoveAnimation( i , j , i , k );
                         board[i][k] = board[i][j] ;
                         board[i][j] = 0 ;
                         continue;
                     }
                     else if( board[i][k] == board[i][j] && noBlockHorizontal( i , k , j , board)  && !hasConflicted[i][k] ){
                         //可以移动
                         showMoveAnimation( i , j , i , k );
                         board[i][k] += board[i][j] ;
                         board[i][j] = 0 ;
                         score += board[i][k] ;
                         updateScore(score) ;
                         hasConflicted[i][k] = true;
                         continue;
                     }
                 }
             }
         }
     }
     setTimeout("updateBoardView()",200);
     return true;
 }

 function moveUp() {

     if (!canMoveUp(board)) {
         return false;
     }

     //moveUp
     for (var i = 1; i < 4; i++) {
         for ( var j = 0; j < 4; j++ ) {
             if (board[i][j] != 0) {
                 for (var k = 0; k < i; k++) {

                     if (board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
                         showMoveAnimation(i, j, k, j);
                         board[k][j] = board[i][j];
                         board[i][j] = 0;
                         continue;
                     }
                     else if (board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasConflicted[k][j]) {
                         showMoveAnimation(i, j, k, j);
                         board[k][j] += board[i][j];
                         board[i][j] = 0;
                         score += board[k][j];
                         updateScore(score);
                         hasConflicted[k][j] = true;
                         continue;
                     }
                 }
             }
         }
     }
    setTimeout("updateBoardView()",200);
    return true;
}

 function moveRight(){
     if( !canMoveRight( board )){
         return false;
     }
     //向右移动
     for( var i = 0 ; i < 4 ; i++ ){
         for( var j = 2 ; j >= 0 ; j -- ){
             if( board[i][j] != 0){
                 for( var k = 3 ; k > j ; k -- ){

                     if( board[i][k] == 0 && noBlockHorizontal( i , j , k , board ) ){
                         //可以移动
                         showMoveAnimation( i , j , i , k );
                         board[i][k] = board[i][j] ;
                         board[i][j] = 0 ;
                         continue;
                     }
                     else if( board[i][k] == board[i][j] && noBlockHorizontal( i , j , k , board ) && !hasConflicted[i][k]){
                         //可以移动
                         showMoveAnimation( i , j , i , k );
                         board[i][k] += board[i][j] ;
                         board[i][j] = 0 ;
                         score += board[i][k] ;
                         updateScore(score) ;
                         hasConflicted[i][k] = true
                         continue;
                     }
                 }
             }
         }
     }
     setTimeout("updateBoardView()",200);
     return true;
 }

 function moveDown(){
     if( !canMoveDown(board)){
         return false;
     }
     //向上移动
     for( var i = 2 ; i >= 0 ; i -- ){
         for( var j = 0 ; j < 4 ; j++ ){
             if( board[i][j] != 0 ){
                 for( var k = 3 ; k > i ; k-- ){
                     if( board[k][j] == 0 && noBlockVertical( j , i , k , board )){
                         //可以移动
                         showMoveAnimation( i , j , k , j );
                         board[k][j] = board[i][j] ;
                         board[i][j] = 0 ;
                         continue;
                     }
                     else if( board[k][j] == board[i][j] && noBlockVertical( j , i , k , board ) && !hasConflicted[k][j]){
                         showMoveAnimation( i , j , k , j);
                         board[k][j] += board[i][j] ;
                         board[i][j] = 0 ;
                         score += board[k][j] ;
                         updateScore(score) ;
                         hasConflicted[k][j] = true;
                         continue;
                     }
                 }
             }
         }
     }
     setTimeout("updateBoardView()",200);
     return true;
 }